// FileImage.h
// By Jayson Adams
// NeXT Strategic Developer Engineer
//
// You may freely copy, distribute and reuse the code in this example.
// NeXT disclaims any warranty of any kind, expressed or implied, as to its
// fitness for any particular use.

#import <libc.h>			// for free()
#import <sys/param.h>			// for MAXPATHLEN
#import <appkit/NXImage.h>
#import <appkit/Speaker.h>
#import <appkit/Listener.h>
#import <appkit/Panel.h>		// for NXRunAlertPanel()
#import <appkit/Application.h>

#import "FileImage.h"


@implementation FileImage


- initForImage:anImage fileName:(const char *)name
{
    [super init];
    
  /* save our graphic image and the file we represent */
    image = anImage;
    fileName = NXCopyStringBuffer(name);
    
    return self;
}

- free
{
    free(fileName);
    return [super free];
}

- readRichText:(NXStream *)stream forView:view
{
    char	stringBuffer[MAXPATHLEN], *currentPosition, nextChar,
    		*tiffBuffer;
    int		length, flag;
    NXStream	*imageStream;
    
  /* get and remember the file name */
    currentPosition = stringBuffer;
    while ((nextChar = NXGetc(stream)) != '\n') {
        *(currentPosition++) = nextChar;
    }
    *currentPosition = '\0';
    fileName = NXCopyStringBuffer(stringBuffer);

  /* ask the Workspace for its icon */
    [[NXApp appSpeaker] setSendPort:NXPortFromName(NX_WORKSPACEREQUEST, NULL)];
    [[NXApp appSpeaker] getFileIconFor:fileName TIFF:&tiffBuffer
    			TIFFLength:&length ok:&flag];

  /* copy the image into our NXImage */
    imageStream = NXOpenMemory(tiffBuffer, length, NX_READONLY);
    image = [[NXImage alloc] initFromStream:imageStream];
    
    NXCloseMemory(imageStream, NX_FREEBUFFER);

    return self;
}

- writeRichText:(NXStream *)stream forView:view
{
  /* 
   * for files, we write the file name;  this isn't a robust solution since
   * the file may not be present when the user reopens the RTF file
   */
    NXPrintf(stream, "%s\n", fileName);
    
    return self;
}

- performDoubleClickAction
{
    int		ok;
    
    [[NXApp appSpeaker] setSendPort:NXPortFromName(NX_WORKSPACEREQUEST, NULL)];
    [[NXApp appSpeaker] openFile:fileName ok:&ok];
    
    if (!ok) {
        NXRunAlertPanel(NULL, "Couldn't open %s", NULL, NULL, NULL, fileName);
    }
    
    return self;
}

@end
